import React, { useEffect, useState } from 'react';
import { Select, Switch } from 'antd';
import _ from 'lodash';
import { useSelector } from 'umi';
import moment from 'moment';
import EchartsWrap from '../../../../widgets/EchartsWrap';
import { getEpidemicData } from '../../../../../services/kanbanServices';
import styles from '../index.less';

const Option = Select.Option;

const typeArr = ['入场数', '体温测量数', '绿码报备数', '接种疫苗数'];

const option = {
  backgroundColor: 'transparent',
  title: [],
  color: [
    'rgba(47, 176, 255, 1)',
    'rgba(47, 243, 255, 1)',
    'rgba(47, 255, 159, 1)',
    'rgba(255, 221, 47, 1)',
  ],
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      crossStyle: {
        color: '#999',
      },
      lineStyle: {
        type: 'dashed',
      },
    },
  },
  grid: {
    left: '25',
    right: '25',
    bottom: '24',
    top: '75',
    containLabel: true,
  },
  legend: {
    data: typeArr,
    orient: 'horizontal',
    icon: 'circle',
    itemWidth: 6,
    itemHeight: 6,
    textStyle: {
      color: 'rgba(255,255,255,0.65)',
    },
    show: true,
    left: 25,
    top: 25,
  },
  xAxis: {
    type: 'category',
    data: [],
    splitLine: {
      show: false,
    },
    axisLabel: {
      show: true,
      itemStyle: {
        fontSize: 12,
        color: 'rgba(255,255,255,0.45)',
      },
    },
    axisTick: {
      show: false,
    },
    axisLine: {
      show: false,
    },
  },
  yAxis: {
    type: 'value',
    // max: max_value>=100? max_value + 100: max_value+10,
    // max: max_value > 100 ? max_value * 2 : max_value + 10,
    // interval: 10,
    // nameLocation: "center",
    axisLabel: {
      color: 'rgba(255,255,255,0.45)',
      textStyle: {
        fontSize: 12,
      },
    },
    splitLine: {
      show: true,
      lineStyle: {
        color: 'rgba(255,255,255,0.12)',
        type: 'dashed',
      },
    },
    axisTick: {
      show: false,
    },
    axisLine: {
      show: false,
    },
  },
  series: [
    {
      name: typeArr[0],
      type: 'line',
      // data: [13, 1, 4, 44, 45, 322, 76],
      data: [],
    },
    {
      name: typeArr[1],
      type: 'line',
      // data: [13, 54, 34, 344, 35, 53],
      data: [],
    },
    {
      name: typeArr[2],
      type: 'line',
      // data: [13, 2, 2, 32, 123, 23, 136],
      data: [],
    },
    {
      name: typeArr[3],
      type: 'line',
      // data: [13, 2, 2, 32, 123, 23, 136],
      data: [],
    },
  ],
};

function filterAllDate(data) {
  return _.uniqBy(data, 'date')
    .map(d => d.date)
    .sort((a, b) => {
      return moment(a).valueOf() - moment(b).valueOf();
    });
}

function normalizeDataByDate(data, dates) {
  const ret = [[], [], [], []];

  _.each(dates, d => {
    const dd = _.find(data, i => i.date === d);
    if (dd) {
      ret[0].push(dd.enterCount || 0);
      ret[1].push(dd.temperatureCheckCount || 0);
      ret[2].push(dd.greenCodeCount || 0);
      ret[3].push(dd.vaccinationCount || 0);
    } else {
      ret[0].push(0);
      ret[1].push(0);
      ret[2].push(0);
      ret[3].push(0);
    }
  });

  return ret;
}

/**
 * 疫情防控
 * @returns
 */
const EpidemicControl = () => {
  function getInitialOption() {
    const now = moment();
    const dates = [];
    option.xAxis.data = [];
    for (let i = -6; i <= 0; i += 1) {
      const day = now.clone().add(i, 'd');
      dates.push(day.format('MM-DD'));
    }
    option.xAxis.data.push(...dates);

    return option;
  }

  const [data, setData] = useState(getInitialOption());
  const [showEmergency, setEmergency] = useState(true);
  const [curProj, setCurProj] = useState('-1');
  const sysProjList = useSelector(store => {
    return store.kanban.projList;
  });

  // function refreshChart() {
  //   setData({ ...data });
  // }

  function initChart(project, isEmergency) {
    getEpidemicData(project, isEmergency).then(response => {
      const responseData = response && response.data;
      if (responseData && responseData.code === 200 && responseData.success) {
        const { data } = responseData;
        // const data = [
        //   {
        //     date: '2021-09-15',
        //     enterCount: 1,
        //     greenCodeCount: 1,
        //     temperatureCheckCount: 1,
        //     vaccinationCount: 1,
        //   },
        //   {
        //     date: '2021-09-16',
        //     enterCount: 2,
        //     greenCodeCount: 1,
        //     temperatureCheckCount: 1,
        //     vaccinationCount: 1,
        //   },
        // ];
        if (!data.length) {
          const _option = getInitialOption();
          _option.series.forEach(e => {
            e.data = [];
          });
          setData(_.cloneDeep(_option));
          return;
        }
        if (_.isArray(data)) {
          const dates = filterAllDate(data);

          while (option.xAxis.data.length) {
            option.xAxis.data.pop();
          }
          option.xAxis.data.push(...dates);

          const normalData = normalizeDataByDate(data, dates);
          for (let i = 0; i < 4; i += 1) {
            option.series[i].data = normalData[i];
          }

          console.log(option);

          setData(_.cloneDeep(option));
          // refreshChart();
        }
      }
    });
  }

  useEffect(() => {
    if (sysProjList && sysProjList.length > 0) {
      // setCurProj('1424561968071168001');
    }
  }, [sysProjList]);

  useEffect(() => {
    // if (!curProj) {
    //   return;
    // }

    initChart(curProj == -1 ? '' : curProj, showEmergency);
  }, [curProj, showEmergency]);

  return (
    <div className="chart-box" style={{ width: 450 }}>
      <div className="chart-box-title">
        <span className={styles.chartHead}>
          <span>疫情防控</span>
          <span>
            <span className={styles.chartHeadHint} style={{ display: 'none' }}>
              重点
            </span>
            {/* <Switch
              size={'small'}
              style={{ display: 'none' }}
              checkedChildren={'是'}
              unCheckedChildren={'否'}
              checked={showEmergency}
              onChange={value => setEmergency(value)}
            /> */}
            <Select
              placeholder={'项目选择'}
              style={{ width: 96 }}
              dropdownMatchSelectWidth={false}
              value={curProj}
              onChange={value => setCurProj(value)}
              disabled={!sysProjList.length}
            >
              <Option value={'-1'}>{'全部'}</Option>
              {sysProjList.map(prj => {
                return <Option value={prj.projectId}>{prj.projectName}</Option>;
              })}
            </Select>
          </span>
        </span>
      </div>
      <div className="chart-box-body">
        <EchartsWrap option={data} style={{ width: '450px', height: '250px' }} />
      </div>
    </div>
  );
};

export default EpidemicControl;
